﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

using EShop.Core;
using EShop.Core.Caching;
using EShop.Core.Data;
using EShop.Core.Events;
using EShop.Core.Model.Store;
using EShop.Data;
using System.Data.SqlClient;
using System.Data;

namespace EShop.Services.Store
{
    public class ProductService : IProductService
    {

        #region Constants
        private const string PRODUCT_BY_ID_KEY = "Product.id-{0}";
        private const string PRODUCT_PATTERN_KEY = "Product";
        #endregion

        #region Fields
        private readonly IRepository<Product> _productRepository;
        private readonly ICacheManager _cacheManager;
        private readonly IEventPublisher _eventPublisher;
        private readonly IDbContext _dbContext;
        //private readonly IDbContext _context;
        #endregion

        #region Ctor
        public ProductService(IRepository<Product> productRepository, ICacheManager cacheManager, IEventPublisher eventPublisher, IDbContext dbContext)
        {
            _productRepository = productRepository;
            _cacheManager = cacheManager;
            _eventPublisher = eventPublisher;
            this._dbContext = dbContext;
        }
        #endregion

        /// <summary>
        /// 查询商品，单个
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public Product GetProductById(string id)
        {
            if (string.IsNullOrEmpty(id))
                return null;
            //格式化缓存条件
            string key = string.Format(PRODUCT_BY_ID_KEY, id);
            return _cacheManager.Get(key, () =>
            {
                var product = _productRepository.GetById(id);
                return product;
            });

        }

        /// <summary>
        /// 添加商品
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        public bool AddProduct(Product model)
        {

            if (model == null) throw new ExtException("NUll Product Model");

            int rs = _productRepository.Insert(model);
            if (rs > 0)
            {
                //event notification
                _eventPublisher.EntityInserted(model);

            }
            return rs > 0 ? true : false;
        }

        /// <summary>
        /// 修改商品
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        public bool UpdateProduct(Product model)
        {
            if (model == null) throw new ExtException("NUll Product Model");

            int rs = _productRepository.Update(model);
            if (rs > 0)
            {
                //event notification
                _eventPublisher.EntityInserted(model);

            }
            return rs > 0 ? true : false;
        }

        /// <summary>
        /// 删除商品
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public bool DelProduct(string id)
        {
            var model = _productRepository.GetById(id);
            if (model == null)
                throw new ArgumentNullException("NUll Product Model");

            //model.Published = false;
            int r = _productRepository.Update(model);

            if (r > 0)
            {
                //cache
                _cacheManager.RemoveByPattern(PRODUCT_PATTERN_KEY);

                //event notification
                _eventPublisher.EntityUpdated(model);
            }
            return r > 0 ? true : false;
        }

        /// <summary>
        /// 取得一条商品信息jsons
        /// </summary>
        /// <param name="id"></param>
        /// <param name="isjson"></param>
        /// <returns></returns>
        public string GetProductByid(string id, bool isjson)
        {
            //if (string.IsNullOrEmpty(id))
            //    return null;
            ////格式化缓存条件
            //string key = string.Format(PRODUCT_BY_ID_KEY, id);
            //return _cacheManager.Get(key, () =>
            //{
            //    var product = _productRepository.GetById(id);
            //    return product;
            //});
            throw new NotImplementedException();
        }



        public PagedList<ProductList> GetAllProduct(int pageIndex, int pageSize, string sortDirection, string sortField, int? selectSearch, string searchStr)
        {
            var pTotalRecords = new SqlParameter { ParameterName = "TotalRecords", Direction = ParameterDirection.Output, SqlDbType = SqlDbType.Int };
            var receiptInformation = _dbContext.ExecuteStoredProcedureListWithoutAttach<ProductList>(
             "SearchProduct",
             new SqlParameter { ParameterName = "SelectSearch", Value = selectSearch, SqlDbType = SqlDbType.Int },
             new SqlParameter { ParameterName = "SearchStr", Value = searchStr, SqlDbType = SqlDbType.NVarChar },
             new SqlParameter { ParameterName = "PageIndex", Value = pageIndex, SqlDbType = SqlDbType.Int },
             new SqlParameter { ParameterName = "PageSize", Value = pageSize, SqlDbType = SqlDbType.Int },
             new SqlParameter { ParameterName = "SortField", Value = sortField, SqlDbType = SqlDbType.NVarChar },
             new SqlParameter { ParameterName = "SortDirection", Value = sortDirection, SqlDbType = SqlDbType.NVarChar }, pTotalRecords);
            int totalRecords = (pTotalRecords.Value != DBNull.Value) ? Convert.ToInt32(pTotalRecords.Value) : 0;
            return new PagedList<ProductList>(receiptInformation, pageIndex, pageSize, totalRecords);
        }

    }
}
